import { GCtrl } from "../../../Core/GCtrl";
import GParam from "../../../Core/GEvent/GParam";
import GPage from "../../../Core/GView/GPage";
import { tyqSDK } from "../../../tyq/tyq-sdk";
import { CMsg, RedpointEffect, RPointMask } from "../../Common/Define";
import TimeUtil from "../../Common/TimeUtils";
import { VIEW_ID } from "../../Common/UI";
import UICreate from "../../Common/UICreate";
import { Res } from "../../Common/UIResources";
import GameMgr from "../../Logic/GameMgr";
import hangPage from "../Common/HangPage";
import TopUiItem from "../Common/TopUiItem";
import ChapterPage from "./ChapterPage";

const { ccclass, property, menu, executeInEditMode } = cc._decorator;
@ccclass @menu('View/Home/MainCtrl')

export default class MainCtrl extends GPage {

	/**当前页面索引 */
	private _index: number = 0;
	/**最大页面索引 */
	private _maxIndex: number = 0;

	@property({
		type: cc.PageView,
		tooltip: "章节滚动视图"
	})
	pageView: cc.PageView = null;

	@property({
		type: cc.PageView,
		tooltip: "章节标题滚动视图"
	})
	pageView1: cc.PageView = null;

	@property({
		type: cc.Node,
		tooltip: "翻页父节点"
	})
	content: cc.Node = null;

	@property({
		type: cc.Node,
		tooltip: "背景"
	})
	bg: cc.Node = null;

	@property({
		type: cc.Node,
		tooltip: "宝箱"
	})
	box: cc.Node = null;

	@property({
		type: cc.Label,
		tooltip: "在线时长"
	})
	lineLab: cc.Label = null;

	@property({
		type: cc.Node,
		tooltip: "宝箱领取"
	})
	recive: cc.Node = null;

	@property({type: cc.Node,tooltip: "在线宝箱"})  lineBox: cc.Node = null;

	@property({ type: sp.Skeleton, tooltip: "漂浮小岛" }) sk_dao: sp.Skeleton = null;

	@property({type: cc.Node,tooltip: "伸缩模块"})  bottomNode: cc.Node = null;

	@property({type: cc.Node,tooltip: "伸缩按钮"})  backBtn: cc.Node = null;

	private isTouch: boolean = true;
	private snow = [];
	protected onLineReward: number[] = [];
	private onLine: number = 0;

	private isHide:boolean = false;

	protected onVipBtnClick() {
		GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.vip);
		GCtrl.ES.emit(CMsg.client.home.onVipLvUp, new GParam(GameMgr.lUserData.vipLv));
	}

	protected onSignInBtnClick() {
		GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.sginIn);
	}

	protected onOfficerBtnClick() {
		GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.officer);
	}

	protected onSportsCtrlBtnClick() {
		let curLevel = GameMgr.lUserData.level;
		if (curLevel < 5) {
			return GameMgr.uiMgr.showToast("竞技场在通关5关后开启");
		}
		GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.towerCtrl);
	}

	onGLoad() {


		let openId = cc.sys.localStorage.getItem('tyq_item_openid');
		// console.log("tyq_item_openid", openId);
		tyqSDK.login();
		GCtrl.ES.on(CMsg.client.home.onChangeLevel, this, this.changeLevel.bind(this));
		GameMgr.redMgr.on(this.node, [
			{ mask: [RPointMask.RPM_Vip_Daily, RPointMask.RPM_Vip_Frist], subPath: "bg/vipBtn", effectType: RedpointEffect.REDPOINT },
			{ mask: [RPointMask.RPM_Office], subPath: "bg/BaronBtn", effectType: RedpointEffect.REDPOINT },
			{ mask: [RPointMask.RPM_Sign], subPath: 'bg/SignInBtn', effectType: RedpointEffect.REDPOINT },
			{ mask: [RPointMask.RPM_Tower], subPath: "bg/sports", effectType: RedpointEffect.REDPOINT },
		])
		this.node.setContentSize(cc.winSize);
		this.initChapterView();
		this.addHang();
		// GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.sginIn);
		this.onLine = GameMgr.lUserData.getOnLine();//在线时长
		GameMgr.lUserData.setOnLine(this.onLine);//是否同一天
		if (!GameMgr.lUserData.onLineDayDate()) {
			this.onLine = 0;
		}
		GameMgr.lUserData.onLineTime();
		this.initLeftTime();
		GCtrl.ES.on(GCtrl.GTimerSecondEventMsg, this, this.initLeftTime.bind(this));




	}

	/**全局时间 */
	protected initLeftTime() {
		if (!GameMgr.lUserData.onLineDayDate()) {
			GameMgr.lUserData.onLineTime();
			this.onLine = 0;
		}
		// var timenow = new Date(GCtrl.now);
		// var second = timenow.getHours() * 3600; //小时
		// second += timenow.getMinutes() * 60;//分钟
		// second += timenow.getSeconds(); //秒
		// var remain = second; //剩余秒 
		this.onLine += 1;
		var onLineReward = GameMgr.onLineAwardData.isReceiveReward(this.onLine);
		if (onLineReward.bool) {
			let box = this.box.getComponent(cc.Animation);
			box.play('boxShake');
			this.box.children[0].active = true;
			this.lineLab.node.active = false;
			this.recive.active = true;
			// box.playOnLoad = true;
		} else {
			this.recive.active = false;
			this.box.children[0].active = false;
			this.lineLab.node.active = true;
			let box = this.box.getComponent(cc.Animation);
			box.stop();
			this.box.children[0].active = false;
		}

		if (GameMgr.lUserData.onLineAddNum > GameMgr.onLineAwardData.maxTimeId) {
			this.lineLab.string = '';

			let num = GameMgr.lUserData.getOnLineRewardNum();
			let bool = GameMgr.onLineAwardData.isAllReward(num);
			if (bool) {
				this.lineBox.active = false;
			}

		} else {
			let time = GameMgr.lUserData.onLineAddNum;
			GameMgr.lUserData.setOnLine(this.onLine);
			if (GameMgr.onLineAwardData.getRaw<SOnLineAwardDataRaw>(time).time - this.onLine < 0) {
				// console.log("GameMgr.lUserData.onLineAddNum", time);
				GameMgr.lUserData.setOnLineAdd();
			} else {
				this.lineLab.string = TimeUtil.formatClock(GameMgr.onLineAwardData.getRaw<SOnLineAwardDataRaw>(time).time - this.onLine, "hh:mm:ss");
			}
		}
	}

	/**在线宝箱 */
	public onLineBox() {
		var onLineReward = GameMgr.onLineAwardData.isReceiveReward(this.onLine);
		if (onLineReward.bool) {
			GameMgr.lUserData.setOnLineRewardNum();
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rewardCtrl, onLineReward.reward);
			// GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.timeBox)
		} else {
			let time = TimeUtil.formatClock(GameMgr.onLineAwardData.getRaw<SOnLineAwardDataRaw>(onLineReward.index).time - this.onLine, "hh:mm:ss");
			GameMgr.uiMgr.showToast('时间未到，' + time + '后可以领取');
		}
		// this.assetImpl.prefab(Res.prefab.item.previewCtrl, (prefab: cc.Prefab) => {
		// 	let previewCtrl = cc.instantiate(prefab);
		// 	this.node.addChild(previewCtrl);
		// })
	}

	onPageIn() {
		GCtrl.ES.emit(CMsg.client.home.onaddLevel);
	}

	start() {

	}

	protected changeLevel(_d, index) {
		this.pageView.setCurrentPageIndex(index);
		if (this.snow[index] == 1) {
			this.sk_dao.setAnimation(0, '1', true)
		}
		if (this.snow[index] == 2) {
			this.sk_dao.setAnimation(0, '2', true)
		}
	}

	public addHang() {
		/**顶部UI */
		this.addGChild<TopUiItem>(Res.prefab.item.topUiItem, (comp: TopUiItem) => {
			comp.node.parent = GameMgr.uiMgr.uiRoot;
			//comp.node.parent = this.bg;
			let winSize = cc.winSize;
			// comp.node.setPosition(cc.v2(-winSize.width / 2, winSize.height / 2));

			comp.node.setPosition(cc.v2(-winSize.width / 370, winSize.height / 2.16));
			let hang = comp.addComponent(hangPage);
			hang.addListenPage([VIEW_ID.home, VIEW_ID.heroPage, VIEW_ID.chuangguanView, VIEW_ID.chuangguanView, VIEW_ID.bagView],
				[VIEW_ID.officer, VIEW_ID.levelCtrl, VIEW_ID.blessCtrl, VIEW_ID.towerCtrl, VIEW_ID.fightLayer, VIEW_ID.detailsCtrl]);
		});
	}



	protected initChapterView() {
		let arrs: SStoryDataRaw[][] = [];
		GameMgr.storyData.data.forEach((data: SStoryDataRaw, index: number) => {
			let idx = data.section - 1;
			if (arrs[idx]) {
				let arr = arrs[idx];
				arr.push(data);
			} else {
				let arr = [data];
				arrs.push(arr)
			}
		})
		let arrIndex = GameMgr.storyData.getSection();
		this.snow = GameMgr.storyData.getSnow();
		this.assetImpl.prefab(Res.prefab.vw.home.chapterPage, (prefab) => {
			arrIndex.forEach((v, count) => {
				let spr = UICreate.sprite();
				this.assetImpl.spriteFrame(spr.getComponent(cc.Sprite), Res.bigpic.main + "level_" + v);
				this.pageView1.addPage(spr.node);
				let comp = this.assetImpl.addGChild<ChapterPage>(prefab)
				this.pageView.addPage(comp.node);
				comp.initData(arrs[count], count);
			})

			// arrs.forEach((arr, index) => {
			// 	let comp = this.assetImpl.addGChild<ChapterPage>(prefab)
			// 	this.pageView.addPage(comp.node);
			// 	comp.initData(arr, index);
			// })
			GCtrl.ES.emit(CMsg.client.home.onaddLevel);
		})


	}

	/**下一页 */
	protected nextPage() {
		if (!this.isTouch) {
			return;
		}
		this.isTouch = false;
		this.scheduleOnce(() => {
			this.isTouch = true;
		}, 0.3);
		this._maxIndex = this.content.children.length;
		this._index = this.pageView.getCurrentPageIndex();
		this._index++;
		if (this._index >= this._maxIndex) {
			this._index = this._maxIndex;
		}
		this.pageView1.setCurrentPageIndex(this._index);
		this.pageView.setCurrentPageIndex(this._index);
		if (this.snow[this._index] == 1) {
			this.sk_dao.setAnimation(0, '1', true)
		}
		if (this.snow[this._index] == 2) {
			this.sk_dao.setAnimation(0, '2', true)
		}
	}

	/**上一页 */
	protected previousPage() {
		if (!this.isTouch) {
			return;
		}
		this.isTouch = false;
		this.scheduleOnce(() => {
			this.isTouch = true;
		}, 0.3);
		this._index = this.pageView.getCurrentPageIndex();
		this._index--;
		if (this._index <= 0) {
			this._index = 0;
		}
		this.pageView1.setCurrentPageIndex(this._index);
		this.pageView.setCurrentPageIndex(this._index);
		if (this.snow[this._index] == 1) {
			this.sk_dao.setAnimation(0, '1', true)
		}
		if (this.snow[this._index] == 2) {
			this.sk_dao.setAnimation(0, '2', true)
		}
	}

	protected onStartFight() {
		GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.levelCtrl, (this._index + 1))
		// let isNoHero = GameMgr.rHeroData.checkInNoHero();
		// if (isNoHero) {
		// 	GameMgr.uiMgr.showToast(JXLocales.fight.teamEmpty);
		// 	return;
		// }
		// let args: ArgsBattleViewCtrl<any> = {
		// 	sceneId: PART_BTL_SCENE.GUANQIA,
		// }
		// GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.fightLayer, args)
	}

	update() {
		//这个千万不能删
		this.pageView._unregisterEvent();
		this.pageView1._unregisterEvent();
	}

	public onClickHandler(event:any, str:string){
		if (event.target._name == "activityBtn"){

		}
		else if (event.target._name == "backBtn"){
			if (this.isHide){
				this.isHide = false
				cc.tween(this.bottomNode).to(0.3,{position:cc.v2(0, 0)}).start()
				this.backBtn.scaleX = -1;
			}else{
				this.isHide = true
				cc.tween(this.bottomNode).to(0.3,{position:cc.v2(250, 0)}).start()
				this.backBtn.scaleX = 1;
			}
		}
		else if (event.target._name == "setingBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.setting);
		}
		else if (event.target._name == "friendBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.friendView);
		}
		else if (event.target._name == "emailBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.emailView);
		}
		else if (event.target._name == "rankBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.rankCtrl);
		}
		else if (event.target._name == "heroBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.dianjiangView);
		}
		else if (event.target._name == "jiuguanBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.jiuguanView);
		}
		else if (event.target._name == "shopBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.shopView);
		}
		else if (event.target._name == "juntuanBtn"){
			GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.juntuanView);
		}
	}
}	